package org.dromara.comm_lhz.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.dromara.comm_lhz.entity.AsAuthenticationInformationEntity;
import org.dromara.comm_lhz.entity.AsTotalOrderEntity;
import org.dromara.comm_lhz.mapper.AsTotalOrderHMapper;
import org.dromara.comm_lhz.service.AsAuthenticationInformationHService;
import org.dromara.comm_lhz.service.AsPointsManagementHService;
import org.dromara.comm_lhz.service.AsTotalOrderHService;
import org.dromara.comm_lhz.util.QiniuUtil;
import org.dromara.comm_lhz.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

@Service
public class AsTotalOrderHServiceImpl extends ServiceImpl<AsTotalOrderHMapper, AsTotalOrderEntity> implements AsTotalOrderHService {


    @Autowired
    private AsAuthenticationInformationHService asAuthenticationInformationHService;
    @Autowired
    private QiniuUtil qiniuUtil;
    @Autowired
    private AsPointsManagementHService asPointsManagementHService;


    @Override
    public void addTotalOrder(AsTotalOrderEntity asTotalOrderEntity) {
        // 获取当前时间作为订单创建时间
        Date createTime = new Date();

        // 设置订单的创建时间和更新时间
        asTotalOrderEntity.setCreateTime(createTime);
        asTotalOrderEntity.setUpdateTime(createTime);

        // 生成订单编号（可以使用当前时间戳或其他规则）
        String orderNumber = String.valueOf(System.currentTimeMillis());
        asTotalOrderEntity.setOrderNumber(orderNumber);


        // 计算总价格
        Double sumPrice = asTotalOrderEntity.getPrice() * asTotalOrderEntity.getNum();
        asTotalOrderEntity.setSumPrice(sumPrice);


        // 从认证信息表中获取用户的地址信息
        AsAuthenticationInformationEntity authInfo = asAuthenticationInformationHService.getById(asTotalOrderEntity.getUserId());
        if (authInfo != null) {
            asTotalOrderEntity.setOrderAddress(authInfo.getRegion() + " " + authInfo.getRoomNo());
            asTotalOrderEntity.setCreateBy(authInfo.getName());
        }

        // 保存订单到数据库
        this.save(asTotalOrderEntity);
    }

    @Override
    public void updateTotalOrder(AsTotalOrderEntity asTotalOrderEntity) {
        // 更新订单信息
        this.updateById(asTotalOrderEntity);
    }

    /**
     * 支付
     *
     * @param asTotalOrderEntity
     */
    @Override
    public void updateTotalOrderPay(AsTotalOrderEntity asTotalOrderEntity) {
        // 检查实体对象是否存在
        if (asTotalOrderEntity == null || asTotalOrderEntity.getId() == null) {
            throw new IllegalArgumentException("订单实体或订单ID不能为空");
        }


        // 计算总价格
        if (asTotalOrderEntity.getPrice() != null && asTotalOrderEntity.getNum() != null) {
            Double sumPrice = asTotalOrderEntity.getPrice() * asTotalOrderEntity.getNum();
            asTotalOrderEntity.setSumPrice(sumPrice);
        }

        // 设置核销期限为三天后
        if (asTotalOrderEntity.getVerificationDate() == null) {
            Date createTime = new Date();
            Date verificationDeadline = new Date(createTime.getTime() + 3L * 24 * 60 * 60 * 1000); // 3天的毫秒数
            asTotalOrderEntity.setVerificationDate(verificationDeadline);
        }

        // 设置核销码（可以使用随机生成或其他方式）
        if (asTotalOrderEntity.getVerificationCode() == null) {
            asTotalOrderEntity.setVerificationCode(generateVerificationCode());
        }

        // 设置核销二维码
        if (asTotalOrderEntity.getVerificationQrCode() == null) {
            try {
                asTotalOrderEntity.setVerificationQrCode(
                    qiniuUtil.uploadImage(convertFileToMultipartFile(QrCodeUtil.generate(
                        asTotalOrderEntity.getVerificationCode(),
                        new QrConfig(600, 600).setErrorCorrection(ErrorCorrectionLevel.H),
                        File.createTempFile("checkoutQRCode", ".jpg")))));
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Failed to generate or upload QR code", e);
            }
        }

        // 更新积分
        asPointsManagementHService.updatePointsPay(asTotalOrderEntity.getUserId(), asTotalOrderEntity.getSumPrice());


        // 更新订单信息
        this.updateById(asTotalOrderEntity);
    }


    /**
     * 将 File 转换为 MultipartFile
     *
     * @param file 要转换的 File 对象
     * @return 转换后的 MultipartFile 对象
     * @throws IOException 如果读取文件出错
     */
    public static MultipartFile convertFileToMultipartFile(File file) throws IOException {
        // 使用 FileInputStream 读取文件
        FileInputStream input = new FileInputStream(file);

        // 创建 MultipartFile 对象
        MultipartFile multipartFile = new MockMultipartFile(
            file.getName(), // 文件名
            file.getName(), // 文件名
            "application/octet-stream", // 文件类型（可根据实际情况修改）
            input // 文件输入流
        );

        // 关闭流
        input.close();

        return multipartFile;
    }


    // 生成核销码的方法（示例）
    private String generateVerificationCode() {
        // 生成一个随机的6位数字核销码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        return String.valueOf(code);
    }
}

